import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
import { Response } from 'express';
import { SYSTEM_MESSAGE } from 'src/common/constant';
import { ExceptionMap, sendExceptionResponse } from 'src/utils';
import * as Mongoose from 'mongoose';
const MongooseError = Mongoose.Error;
/**
 * @description 捕获系统所有mongoose异常
 * @see https://mongoosejs.com/docs/api/error.html#error_Error-CastError
 */
@Catch(MongooseError)
export class MongooseExceptionFilter implements ExceptionFilter {
  catch(exception: Mongoose.Error, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const { statusCode, error } = ExceptionMap.Internal_Server_Error;
    if (exception instanceof MongooseError.CastError) {
      sendExceptionResponse({
        response,
        statusCode: statusCode,
        errorName: error,
        message: SYSTEM_MESSAGE.NOT_MATCH_ID_RULE(exception.value),
        detail: exception.message,
        exception: exception,
      });
    } else {
      sendExceptionResponse({
        response,
        statusCode: statusCode,
        errorName: error,
        message: SYSTEM_MESSAGE.INTERNAL_EXCEPTION, //内部错误
        detail: exception.message,
        exception: exception,
      });
    }
  }
}
